package com.hung.trade.common.client;

import com.hung.trade.common.constants.TradeEnums;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Method;

/**
 * @author hungki
 * @createTime 2018-10-09 上午 12:49
 */
public class RestClientFactoryBeanSpringProxy implements FactoryBean {
    private RestTemplate restTemplate = new RestTemplate();
    private Class serviceInterface;
    private TradeEnums.RestServerEnum serverEnum;

    public void setServiceInterface(Class serviceInterface) {
        this.serviceInterface = serviceInterface;
    }

    public void setServerEnum(TradeEnums.RestServerEnum serverEnum) {
        this.serverEnum = serverEnum;
    }

    @Override
    public Object getObject() throws Exception {
        Object obj =Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{serviceInterface},  new ClientProxy());
        return obj;
    }

    @Override
    public Class<?> getObjectType() {
        return serviceInterface;
    }
    @Override
    public boolean isSingleton() {
        return true;
    }

    private class ClientProxy implements InvocationHandler {
        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            System.out.println("objects = " +objects[0]);
            System.out.println("serverEnum.getServerUrl()+\"/\"+method.getName() = " + serverEnum.getServerUrl()+"/"+method.getName());
            return restTemplate.postForObject(serverEnum.getServerUrl()+"/"+method.getName(),objects[0],method.getReturnType());
        }
    }
}
